package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.common.MessageConstant;
import com.xrit.sunnyday.common.Result;
import com.xrit.sunnyday.pojo.Setmeal;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetMealService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/report")
@RestController
public class ReportController {
    /*
    远程调用
     */
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport.do")
    public Result getMemberReport(){
        //1,通过jdk自带的Calender类获取过去一年
        Calendar calendar = Calendar.getInstance();
        //添加一个年
        calendar.add(Calendar.YEAR,-1);
        //3,创建一个list集合用来装载月份4
        ArrayList<String> month = new ArrayList<>();
        //4,创建SimpleDateFormat
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
        //2,获取过去一年到现在的月份
        for (int i = 0; i < 12; i++) {
            //添加一个月份
            calendar.add(Calendar.MONTH,1);
            //获取calender中的日期
            Date date = calendar.getTime();
            //将date转换成spring类型
            String Stringdate = sdf.format(date);
            month.add(Stringdate);
        }
        //5,调用根据月份查询会员数量的方法
        List<Integer> memberCount=memberService.findByMonth(month);
        //6,创建map集合,将数据封装并返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("months",month);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
    @RequestMapping("/getSetmealReport.do")
    public Result getSetmealReport(){
        List<Map<String,Object>> list=setMealService.findSetMealOrder();
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,list);
    }
    /*
    查询运营数据
     */
    @RequestMapping("/getBusinessReportData.do")
    public Result getBusinessReportData(){
        Map<String, Object> reportData = reportService.findBusiness();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,reportData);
    }
    /*
    导出Excel
     */
    @RequestMapping("/exportBusinessReport.do")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        //1,调用数据库中的查询运营信息的方法
        Map<String, Object> map = reportService.findBusiness();
        String reportDate =(String) map.get("reportDate");
        Integer todayNewMember = (Integer) map.get("todayNewMember");
        Integer weekNewMember = (Integer) map.get("thisWeekNewMember");
        Integer monthNewMember =(Integer) map.get("thisMonthNewMember");
        Integer totalMember = (Integer) map.get("totalMember");
        Integer todayOrderNumber =(Integer) map.get("todayOrderNumber");
        Integer weekOrderNumber =(Integer) map.get("thisWeekOrderNumber");
        Integer MonthOrderNumber =(Integer) map.get("thisMonthOrderNumber");
        Integer todayVisitsNumber =(Integer) map.get("todayVisitsNumber");
        Integer weekVisitsNumber =(Integer) map.get("thisWeekVisitsNumber");
        Integer monthVisitsNumber =(Integer) map.get("thisMonthVisitsNumber");
        List<Map<String, Object>> hotSetmeal =(List<Map<String, Object>>) map.get("hotSetmeal");
        //2,读取Excel文件
        //获取webapp下的report_template文件
        String report_template = request.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        //3,将数据写入Excel文件
        //创建流读取Excel文件
        try (FileInputStream is = new FileInputStream(report_template);
             //创建缓存输出流
             BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
             //创建工作簿,将模板放入
             Workbook workbook = new XSSFWorkbook(is)
        ) {
            //获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //给单元格赋值
            //-----------------会员数据统计------------------------------
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(weekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(monthNewMember);
            //-----------------预约到诊数据统计------------------------------
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(weekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(weekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(MonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(monthVisitsNumber);
            //定义行变量
            int row=12;
            //循环遍热门套餐
            for (Map<String, Object> stringObjectMap : hotSetmeal) {
               //给单元格赋值
                sheet.getRow(row).getCell(4).setCellValue((String) stringObjectMap.get("name"));
                sheet.getRow(row).getCell(5).setCellValue((Long)stringObjectMap.get("setmeal_count"));
                BigDecimal proportion=(BigDecimal)stringObjectMap.get("proportion");
                sheet.getRow(row).getCell(6).setCellValue(proportion.doubleValue());
                sheet.getRow(row).getCell(7).setCellValue((String) stringObjectMap.get("remark"));
                //行+1
                row++;
            }
            //4.将Excel返回给浏览器
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            response.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            response.setContentType("application/vnd.ms-excel");
            //将数据写入
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
